package top.xiaozhaobk.xiaofenshu.oss.biz.strategy.impl;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import top.xiaozhaobk.xiaofenshu.oss.biz.config.MinioProperties;
import top.xiaozhaobk.xiaofenshu.oss.biz.enums.ResponseCodeEnum;
import top.xiaozhaobk.xiaofenshu.oss.biz.strategy.FileStrategy;

import java.util.UUID;

@Slf4j
public class MinioFileStrategy implements FileStrategy {
    @Resource
    private MinioProperties minioProperties;
    @Resource
    private MinioClient minioClient;

    @Override
    public String uploadFile(MultipartFile file, String bucketName) {
        log.info("使用Minio上传文件");

        if (file == null || file.getSize() == 0) {
            log.error("==>上传文件异常：文件大小为空");
            throw new RuntimeException("文件大小不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        //生成文件名称
        String key = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀,substring 方法用于截取字符串，lastIndexOf 方法用于查找最后一个点的位置
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接文件名
        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);
        // 上传文件至 Minio
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build());
        }catch (Exception e) {
            log.error("==> 上传文件至 Minio 失败, ObjectName: {}", objectName);
            throw new RuntimeException(ResponseCodeEnum.PARAM_NOT_VALID.getErrorMessage());
        }

        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), bucketName, objectName);
        log.info("==> 上传文件至 Minio 成功, ObjectName: {}, url: {}", objectName, url);
        return url;
    }
}
